<template>
  <div class="template-detail-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <div>
            <span class="template-title">{{ template.name }}</span>
            <el-tag class="ml-10" :type="template.status === 'published' ? 'success' : 'warning'">
              {{ template.status === 'published' ? '已发布' : '草稿' }}
            </el-tag>
          </div>
          <div>
            <el-button-group>
              <el-button 
                v-if="template.status === 'draft'" 
                type="primary" 
                @click="editTemplate"
              >
                编辑
              </el-button>
              <el-button 
                v-if="template.status === 'published'" 
                type="success" 
                @click="createInstance"
              >
                创建流程
              </el-button>
              <el-button @click="exportTemplate">导出</el-button>
              <el-button @click="goBack">返回</el-button>
            </el-button-group>
          </div>
        </div>
      </template>
      
      <div class="template-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板ID">{{ template.id }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ template.version }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(template.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(template.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ template.description || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="bpmn-container">
        <div class="viewer" ref="viewer"></div>
      </div>
    </el-card>
    
    <!-- 创建流程实例对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建流程实例" width="500px">
      <el-form :model="instanceForm" label-width="120px">
        <el-form-item label="流程类型">
          <el-input v-model="instanceForm.type" disabled></el-input>
        </el-form-item>
        <el-form-item label="变量配置">
          <el-input
            v-model="instanceForm.variablesString"
            type="textarea"
            rows="5"
            placeholder="请输入JSON格式的流程变量，例如: {&quot;key&quot;: &quot;value&quot;}"
          ></el-input>
          <div class="form-tip">JSON格式的流程初始变量</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateInstance">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
// 引入BPMN查看器
import BpmnViewer from 'bpmn-js/lib/NavigatedViewer';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';

const route = useRoute();
const router = useRouter();
const viewer = ref(null);
const loading = ref(false);
const template = ref({
  id: null,
  name: '',
  description: '',
  status: '',
  version: 1,
  created_at: '',
  updated_at: '',
  bpmn_xml: null
});
const createDialogVisible = ref(false);
const instanceForm = ref({
  templateId: null,
  type: '',
  variablesString: '{}'
});
let bpmnViewer = null;

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 加载模板数据
const loadTemplate = async (templateId) => {
  loading.value = true;
  try {
    const response = await axios.get(`/workflow/templates/${templateId}`);
    template.value = response.data;
    
    // 加载BPMN图
    if (template.value.bpmn_xml) {
      await loadBpmnDiagram(template.value.bpmn_xml);
    }
  } catch (error) {
    console.error('加载模板失败:', error);
    ElMessage.error(`加载模板失败: ${error.response?.data?.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 加载BPMN图
const loadBpmnDiagram = async (xml) => {
  if (!viewer.value) return;
  
  // 初始化查看器
  if (!bpmnViewer) {
    bpmnViewer = new BpmnViewer({
      container: viewer.value
    });
  }
  
  try {
    await bpmnViewer.importXML(xml);
    bpmnViewer.get('canvas').zoom('fit-viewport');
  } catch (err) {
    console.error('加载BPMN图失败:', err);
    ElMessage.error('加载BPMN图失败');
  }
};

// 编辑模板
const editTemplate = () => {
  if (template.value.status === 'published') {
    ElMessage.warning('已发布的模板不能编辑，请创建新版本');
    return;
  }
  router.push(`/workflow-editor/${template.value.id}`);
};

// 导出模板
const exportTemplate = () => {
  if (!template.value.bpmn_xml) {
    ElMessage.warning('没有可导出的BPMN图');
    return;
  }
  
  const blob = new Blob([template.value.bpmn_xml], { type: 'application/xml' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${template.value.name || 'workflow'}.bpmn`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 返回列表
const goBack = () => {
  router.push('/workflow-templates');
};

// 打开创建流程实例对话框
const createInstance = () => {
  if (template.value.status !== 'published') {
    ElMessage.warning('只能使用已发布的模板创建流程');
    return;
  }
  
  instanceForm.value = {
    templateId: template.value.id,
    type: template.value.name,
    variablesString: '{}'
  };
  createDialogVisible.value = true;
};

// 提交创建流程实例
const submitCreateInstance = async () => {
  try {
    // 解析JSON字符串为对象
    let variables = {};
    try {
      variables = JSON.parse(instanceForm.value.variablesString);
    } catch (e) {
      return ElMessage.error('变量格式错误，请输入有效的JSON');
    }
    
    const response = await axios.post('/workflow/create', {
      template_id: instanceForm.value.templateId,
      type: instanceForm.value.type,
      variables: variables
    });
    
    ElMessage.success('流程创建成功');
    createDialogVisible.value = false;
    
    // 重定向到流程详情页
    router.push(`/workflow/${response.data.workflow_id}`);
  } catch (error) {
    console.error('创建流程实例失败:', error);
    ElMessage.error(`创建流程实例失败: ${error.response?.data?.message || '未知错误'}`);
  }
};

onMounted(() => {
  const templateId = route.params.id;
  if (templateId) {
    loadTemplate(templateId);
  } else {
    ElMessage.error('未指定模板ID');
    router.push('/workflow-templates');
  }
});
</script>

<style scoped>
.template-detail-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-title {
  font-size: 18px;
  font-weight: bold;
}

.ml-10 {
  margin-left: 10px;
}

.template-info {
  margin-bottom: 20px;
}

.bpmn-container {
  height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 20px;
}

.viewer {
  height: 100%;
  width: 100%;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 